import axios from "axios"
import LocalCache from "@/utils/cache"
import type { AxiosRequestConfig, AxiosInstance, Canceler } from "axios"
import type { IData } from "@/api"
const cancelToken = axios.CancelToken
interface XrequestConfig extends AxiosRequestConfig {
  repeatRequest?: boolean
}
class Xrequest {
  instance: AxiosInstance
  cancel?: Canceler

  constructor(config) {
    this.instance = axios.create(config)
    this.instance.interceptors.request.use(
      (config: XrequestConfig) => {
        if (this.cancel) {
          this.cancel()
        }
        const token = LocalCache.getCache("token")
        if (token) {
          config.headers!.Authorization = token
        }
        if (config.repeatRequest) {
          config.cancelToken = new cancelToken(c => {
            this.cancel = c
          })
        }
        return config
      },
      err => {
        console.log("发送请求错误：", err)
        return err
      }
    )
    this.instance.interceptors.response.use(
      res => {
        return res.data
      },
      err => {
        console.log("响应错误：", err)
        return err
      }
    )
  }
  // 可以传入泛型   告诉ts内部的数据是传入的T的类型
  // 第二个才是response的返回  才需要我们传入的泛型
  request<T = any>(config: XrequestConfig) {
    return this.instance.request<any, IData<T>>(config)
  }
}

export default Xrequest
